﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Globalization;
using System.Configuration;

    /// <summary>
    /// MD5加密。
    /// </summary>
    public class ClassMD5
    {

        public static string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="sInputString">要加密的原文</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        public static string EncryptString(string sInputString)

        {
            string sKey = ConfigurationManager.AppSettings["md5pw"];
            byte[] data = Encoding.UTF8.GetBytes(sInputString);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return BitConverter.ToString(result);
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="sInputString">加密后的密文</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        public static string DecryptString(string sInputString)
        {
            string sKey = ConfigurationManager.AppSettings["md5pw"];
            string[] sInput = sInputString.Split("-".ToCharArray());

            byte[] data = new byte[sInput.Length];

            for (int i = 0; i < sInput.Length; i++)
            {

                data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
            }

            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            ICryptoTransform desencrypt = DES.CreateDecryptor();

            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);

            return Encoding.UTF8.GetString(result);
        }
    }

